package com.kpijavatraining6.module2.questions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
//import java.util.Arrays;
import java.util.ArrayList;
import java.util.Scanner;

public class Reader {
    private String path = "data.txt";


	/**
	 * readStrings reads strings from file
	 * @return array
	 * source stackoverflow
	 * 
	 */
    public Reader(String newPath) {
        path = newPath;
    }

    public ArrayList<QuestionStructure> formQuestionList() {
        ArrayList<QuestionStructure> questionStructures = new ArrayList<QuestionStructure>();
	    File file = new File(path);
	    FileInputStream fin = null;
	    try {
	    	fin = new FileInputStream(file);
	    } catch (FileNotFoundException e) {
	        e.printStackTrace();
    	}
	    Scanner scanner = new Scanner(fin);
	    StringBuffer buffer = new StringBuffer();
        while (scanner.hasNextLine()) {
            String line[] = scanner.nextLine().split(";");
            if (line[0].equals(QuestionStructure.CHECK_ANSWER_TYPE)) {
                questionStructures.add(fillQuestion1(line));
            }
            if (line[0].equals(QuestionStructure.TEXT_ANSWER_TYPE)) {
                questionStructures.add(fillQuestion2(line));
            }
        }
        return questionStructures;
    }

    private CheckAnswerQuestion fillQuestion1(String[] line) {
        String question = line[1];
        String[] answers = line[2].split("\\|");
        String rightAnswer = line[3];
        String[] topicName = line[4].split("\\|");
        int questionLevel = new Integer(line[5]);
        return new CheckAnswerQuestion(question,rightAnswer,questionLevel,answers);
    }

    private WriteAnswerQuestion fillQuestion2(String[] line) {
        String question = line[1];
        String [] rightAnswers = line[2].split(";");
        String[] topicName = line[3].split("\\|");
        int questionLevel = new Integer(line[4]);
        return new WriteAnswerQuestion(question,questionLevel,rightAnswers);
    }
}